package com.css.fxfzypg.modules.baseData.controller;

import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.logInfo.SysLog;
import com.css.fxfzypg.modules.baseData.entity.EmergencyShelter;
import com.css.fxfzypg.modules.baseData.queryParams.EmergencyShelterQueryParams;
import com.css.fxfzypg.modules.baseData.service.EmergencyShelterService;
import com.css.fxfzypg.modules.baseData.queryParams.EmergencyShelterQueryParams;
import com.css.fxfzypg.modules.hypergraph.service.HypergraphService;
import com.css.fxfzypg.modules.maps.queryParams.MapQueryParams;
import com.css.fxfzypg.modules.maps.service.EmergencyShelterMapService;
import com.css.fxfzypg.modules.maps.service.PointGetDivisionService;
import com.css.fxfzypg.modules.qhmapfiles.service.QhMapFilesService;
import com.css.fxfzypg.util.FileUtil;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.PlatformPageUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/fxfzypg/baseData")
@Slf4j
public class EmergencyShelterController {

    @Resource
    EmergencyShelterService emergencyShelterService ;

    @Resource
    EmergencyShelterMapService emergencyShelterMapService;//地图使用

    @Resource
    PointGetDivisionService pointGetDivisionService;

    @Autowired
    private QhMapFilesService qhMapFilesService;//文件管理

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    @Resource
    HypergraphService hypergraphService;

    /**
     * 新增EmergencyShelter
     * @param emergencyShelter
     * @return
     */
    @PostMapping("/saveEmergencyShelter")
    public RestResponse saveEmergencyShelter (@RequestBody EmergencyShelter emergencyShelter){
        RestResponse restResponse = null ;
        try{
            restResponse = RestResponse.succeed(emergencyShelterService.saveEmergencyShelter(emergencyShelter));
        }catch (Exception e){
            log.error("新增应急避难场所数据失败",e);
            restResponse = RestResponse.fail("新增应急避难场所数据失败!");
        }
        return restResponse;
    }

    /**
     * 全查询  模糊查询  名称和地址为条件
     * @param request
     * @param queryParams
     * @return
     */
    @GetMapping("/getAllEmergencyShelter")
    public RestResponse getAllEmergencyShelter(HttpServletRequest request, EmergencyShelterQueryParams queryParams){

        RestResponse restResponse = null;
        try{
//            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
//            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            queryParams.setCurPage(Integer.parseInt(PlatformPageUtils.CUR_PAGE_DEF));
            queryParams.setPageSize(Integer.parseInt(PlatformPageUtils.PAGE_SIZE_DEF));
            restResponse = RestResponse.succeed(emergencyShelterService.getAllEmergencyShelter(queryParams));
        }catch (Exception e){
            log.error("查询应急避难场所数据失败!",e);
            restResponse = RestResponse.fail("查询应急避难场所数据失败");
        }
        return restResponse;
    }

    /**
     * 根据id查询EmergencyShelter数据
     * @param id
     * @return
     */
    @GetMapping("/getEmergencyShelter/{id}")
    public RestResponse<EmergencyShelter> getEmergencyShelter(@PathVariable("id") Integer id) {
        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(emergencyShelterService.getEmergencyShelterById(id));
        }catch (Exception e){
            log.error("获取应急避难场所数据失败!",e);
            restResponse = RestResponse.fail("获取应急避难场所数据失败!");
        }
        return restResponse;
    }


    /**
     * 逻辑删除，修改数据标志位
     * @param ids
     * @return
     */
    @PatchMapping("/delEmergencyShelter/{ids}")
    public RestResponse deleteEmergencyShelter(@PathVariable("ids") List<Integer> ids) {
        RestResponse restResponse = null;
        try{
            emergencyShelterService.deleteEmergencyShelters(ids);
            restResponse = RestResponse.succeed();
        }catch (Exception e){
            log.error("删除应急避难场所数据失败!",e);
            restResponse = RestResponse.fail("删除应急避难场所数据失败!");
        }
        return restResponse;
    }

    /**
     * 修改
     * @param gasstationDataVO
     * @return
     */
//    @PostMapping("/updateGasstationData")
//    public RestResponse<ElevationVO> updateElevation(@RequestBody GasstationDataVO gasstationDataVO)  {
//        RestResponse restResponse = null;
//        try{
//            restResponse = RestResponse.succeed(gasstationDataService.updateGasstationData(gasstationDataVO));
//        }catch (Exception e){
//            log.error("修改失败!",e);
//            restResponse = RestResponse.fail("修改失败!");
//        }
//        return restResponse;
//    }

    /**
     * 导出表内数据
     * @param response
     * @throws IOException
     */
    @PostMapping("/exportExcelEmergencyShelter")
    public void exportExcel(HttpServletResponse response ) throws IOException {
        RestResponse restResponse = null ;
        try{
            List<EmergencyShelter> list  = emergencyShelterService.getAll();
            FileUtil.exportExcel(list, "应急避难场所数据", "sheet", EmergencyShelter.class, "EmergencyShelter", response);
            restResponse = RestResponse.succeed("导出成功");
        }catch (Exception e){
            log.error("导出失败!",e);
            restResponse = RestResponse.fail("导出失败");
        }

    }

    /**
     * 导入数据
     * @param file
     * @throws IOException
     */
    @PostMapping("/importExcelEmergencyShelter")
    public RestResponse importExcel(MultipartFile file) throws IOException {
        RestResponse restResponse = null;
        try {
            emergencyShelterService.importExcel(file);
        } catch (Exception e) {
            log.error("导入数据失败", e);
            restResponse = RestResponse.fail("导入数据失败!");
        }
        return restResponse;
    }


    /*zyt修改--start*/
    /**
     * 全查询  模糊查询未设定条件
     * @param request
     * @param queryParams
     * @return
     */
    @SysLog("地图查询应急避难场所")
    @GetMapping("/getAllEmergencyShelterData")
    public RestResponse getAllEmergencyShelterData(HttpServletRequest request, EmergencyShelterQueryParams queryParams){

        RestResponse restResponse = null;
        try{
            //查询条件
            String province = request.getParameter("province");
            String city = request.getParameter("city");
            String county = request.getParameter("county");
            String fileUuid = request.getParameter("fileUuid");
            String uuid = request.getParameter("uuid");
            queryParams.setProvince(province);
            queryParams.setCity(city);
            queryParams.setCounty(county);
            queryParams.setFileuuid(fileUuid);
            queryParams.setUuid(uuid);
            restResponse = RestResponse.succeed(emergencyShelterMapService.getAllData(queryParams));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }
    /**
     * 根据ID查询数据
     */
    @GetMapping("/getEmergencyShelterDataById/{id}")
    public RestResponse getEmergencyShelterDataById(@PathVariable("id") String id){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(emergencyShelterMapService.getDataById(id));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }
    /**
     * 根据文件ids逻辑删除文件及相关数据
     */
    @PostMapping("/delEmergencyShelterFileData/{ids}")
    public RestResponse delEmergencyShelterFileData(@PathVariable("ids") List<String> ids) {
        RestResponse restResponse = null;
        try{
            String userID = PlatformSessionContext.getUserID();
            emergencyShelterMapService.deleteFileData(ids,userID);
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("sys_emergencyshelter");
            restResponse = RestResponse.succeed("删除成功");
        }catch (Exception e){
            log.error("删除失败!",e);
            restResponse = RestResponse.fail("删除失败!");
        }
        return restResponse;
    }
    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/emergencyShelterUpload")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, MapQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        //if ("".equals(province) ) return RestResponse.fail("请选择场地所在省份!");
        //if ("".equals(city)) return RestResponse.fail("请选择场地所在城市!");
        //if ("".equals(area)) return RestResponse.fail("请选择场地所在区县!");

        //判断是否已上传未保存文件--上传类型（应急避难场所_）
        int fileCount = qhMapFilesService.lookUpMapFiles("0","应急避难场所_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件等待数据入库, 若要上传最新数据请稍后在【管理】功能中删除数据.");

        //判断是否已上传正在保存文件--上传类型（应急避难场所_）
        fileCount = qhMapFilesService.lookUpMapFiles("2","应急避难场所_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件数据正在入库, 若要上传最新数据请稍后在【管理】功能中删除数据.");

        //判断是否已存在上传数据--上传类型（应急避难场所_）
        fileCount = qhMapFilesService.lookUpMapFiles("1","应急避难场所_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【管理】功能中删除数据.");

//        //判断是否已存在上传数据--数据数量查询
//        EmergencyShelterQueryParams emergencyShelterQueryParams = new EmergencyShelterQueryParams();
//        emergencyShelterQueryParams.setProvince(province);
//        emergencyShelterQueryParams.setCity(city);
//        emergencyShelterQueryParams.setCounty(area);
//        int dataCount = emergencyShelterMapService.getAllDataCount(emergencyShelterQueryParams);
//        if(dataCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【管理】功能中删除数据.");

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String gdbFileName = "";//gdb文件名
        String jxfilename = "";//shp文件名
        String dbffilename = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        //判断是否为GDB文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            if (oldFileName.equals("gdb")) {//是否存在gdb文件
                String fName = "新建文件地理数据库";
                String postfix = ".gdb";
                String prefix = "应急避难场所_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                gdbFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                break;
            }
        }

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
                newFileName = gdbFileName + "/"+oldFileName;
            }else {//SHP文件
                // 上传后文件名
                String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
                String prefix = "应急避难场所_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                    jxfilename = newFileName;
                }
                if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                    dbffilename = newFileName;
                }
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                //File _file = new File(uploadPath + newFileName);
                //FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            //returnMsg.append(oldFileName);
            //returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename+gdbFileName);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
            resultMsg = gdbFileName;//返回GDB文件名
            System.out.println(new Date()+"-----------3.开始importGDBFile");
            //resMsg = qhRiskLevelMapService.checkGDBFiles(uploadPath + gdbFileName, province, city, area);
            System.out.println(new Date()+"-----------4.结束importGDBFile");
            if (resMsg.indexOf("spatialReferenceError") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据.");
        }else{//SHP文件
            System.out.println(new Date()+"-----------3.开始importShapeFile");
            resMsg = emergencyShelterMapService.checkSHPFiles(uploadPath + jxfilename, province, city, area, formatDate, userID);
            System.out.println(new Date()+"-----------4.结束importShapeFile");
        }
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            //刷新指定超图工作空间数据源数据集
            boolean bool = hypergraphService.getWorkspaceReload("sys_emergencyshelter");
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);

            if(PlatformObjectUtils.isEmpty(area)){
                pointGetDivisionService.resetDivision("应急避难场所_",province,city);
            }
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "字段值存在空值, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("esIdFormatError") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "Id不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("esTypeFormatError") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "类型不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("esMaxpeopleFormatError") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "可容纳人数不符合字段要求，请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("空间数据类型错误") != -1) return RestResponse.succeed(resMsg.split("#")[0] + resMsg);

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }
    /*zyt修改--end*/
}
